#!/usr/bin/python2.4
#
# Copyright 2007 Google Inc. All Rights Reserved.


__author__ = 'i3dmaster@gmail.com (Yongjian "Jim" Xu)'


import sys
sys.path.append('../')
import unittest
import jsonbuilder
import objson


class JsonBuilderUnitTest(unittest.TestCase):
  def setUp(self):
    self.__j = jsonbuilder.JSON()

  def testRootNode(self):
    self.assertTrue(isinstance(self.__j.root, objson.OBJson))

  def testRootAttribute(self):
    self.assertTrue('version' in self.__j.root.GetAttrs)

  def testSetRoot(self):
    r = objson.OBJson({})
    oldr = self.__j.root
    self.__j.root = r
    self.assertNotEqual(id(oldr), id(self.__j.root))

  def testDelRoot(self):
    del self.__j.root
    self.assertFalse('_JSON__root' in self.__j.__dict__)

  def testRootHasFeed(self):
    self.assertFalse(self.__j.root.HasChild('feed'))

  def testAddSubNode(self):
    f = self.__j.build('feed')
    self.__j.AddSubNode(f)
    author = self.__j.build('author', attrs={'name':{'$t':'foo'},
      'email':{'$t':'foo@com'}})
    self.__j.AddSubNode(author, f)
    self.assertTrue(self.__j.root.feed.HasChild(author))

  def testAddSubNodeToHolderObject(self):
    i = self.__j.build('id', attrs={'id':{'$t':'foo'}})
    self.assertRaises(AttributeError, self.__j.AddSubNode, self.__j, i)

  def testDelSubNodeNotExit(self):
    f = self.__j.build('feed')
    self.assertRaises(objson.OBJsonNoKeyFoundError, self.__j.DelSubNode, \
        f)

  def testDelSubNode(self):
    f = self.__j.build('feed')
    self.__j.AddSubNode(self.__j.root, f)
    self.__j.DelSubNode(self.__j.root, f)
    self.assertFalse(self.__j.root.HasChild('feed'))

  def testNewNoneType(self):
    self.assertRaises(AttributeError, self.__j.build, None)

  def testNewElementWithData(self):
    self.assert_(self.__j.build('id', attrs={'$t':'foo'}))

  def tearDown(self):
    del self.__j

if __name__ == '__main__':
  unittest.main()
